import os
import json
import re
import random
import math
import time
from botpy import logging
from botpy.message import GroupMessage
from tools import send_message, txt_exist, txt_write, player_id, bag_add, bag_reduce, bag_enough
from battle import attribute_count, team_create, team_join, team_leave, team_list, battle_initialization, battle_view, battle_round
from action import move, equip, make_thing, resolve_thing
from list import my_bag, my_attribute, my_equip, my_skill, search_all, make_list, make_infor


async def get_pet(uid, pet_name):
    if not os.path.exists(f"data/pet/{uid}.txt"):
        with open(f"data/pet/{uid}.txt", 'w') as f:
            f.write('[]')
    with open (f"data/pet/{uid}.txt", 'r') as f:
        player_data = json.load(f)
    with open ("data/pet/pet.txt", 'r') as f:
        pet_data = json.load(f)
    found = False
    for player_item in player_data:
        if player_item["名称"] == pet_name:
            get_thing = "{}·精元".format(player_item["名称"])
            await bag_add(uid, get_thing, 1)
            found = True
    if found:
        txt = "【已拥有宠物[{}]，转化为[{}]】".format(pet_name, get_thing)
        return txt
    else:
        found = False
        for pet_item in pet_data:
            if pet_item["名称"] == pet_name:
                new_pet = pet_item
                found = True
                break
        if not found:
            txt = "【不存在该宠物！】"
            return txt
        else:
            new_pet["等级"] = 0
            new_pet["血脉"] = 0
            new_pet["亲密度"] = 0
            new_pet["出战"] = "否"
            new_1 = new_pet["成长基准"]["体质"]
            new_2 = new_pet["成长基准"]["敏捷"]
            new_3 = new_pet["成长基准"]["力量"]
            new_4 = new_pet["成长基准"]["智力"]
            pet_1 = random.uniform(0, new_1)
            pet_2 = random.uniform(0, new_2)
            pet_3 = random.uniform(0, new_3)
            pet_4 = random.uniform(0, new_4)
            new_pet["成长当前"]["体质"] = round(pet_1, 2)
            new_pet["成长当前"]["敏捷"] = round(pet_2, 2)
            new_pet["成长当前"]["力量"] = round(pet_3, 2)
            new_pet["成长当前"]["智力"] = round(pet_4, 2)
            player_data.append(new_pet)
            with open(f"data/pet/{uid}.txt", 'w') as f:
                json.dump(player_data, f, ensure_ascii=False, indent=4)
            txt = "【获得宠物[{}]】".format(pet_name)
            return txt


async def pet_information(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid 
    uid = await player_id(number)
    pet_name = message.content.split("宠物信息")[1]
    txt = "\n===❈宠物信息❈==="
    with open (f"data/pet/{uid}.txt", 'r') as f:
        player_data = json.load(f)
    found = False
    blood_list = {"0": "•劣等•", "1": "◈平庸◈", "2": "✽养晦✽", "3": "✾韬光✾", "4": "✧潜龙✧", "5": "✩开脉✩", "6": "♐鹰势♐", "7": "♋鸣凤♋", "8": "✡返璞✡", "9": "☯归真☯"}
    for player_item in player_data:
        if player_item["名称"] == pet_name:
            skill_txt = "※技能※:"
            for key, value in blood_list.items():
                if key == str(player_item["血脉"]):
                    blood_word = value
                    break
            for skill_item in player_item["技能"]:
                skill_txt += " [{}Lv.{}]".format(skill_item["名称"], skill_item["等级"])
            if len(player_item["技能"]) == 0:
                skill_txt += "【无】"
            txt += "\n【狐】Lv.{}\n[血脉] {}\n[体质] {}+{}({})\n[敏捷] {}+{}({})\n[力量] {}+{}({})\n[智力] {}+{}({})\n————————————\n{}".format(player_item["等级"], blood_word, player_item["基础"]["体质"], player_item["成长当前"]["体质"], player_item["成长基准"]["体质"], player_item["基础"]["敏捷"], player_item["成长当前"]["敏捷"], player_item["成长基准"]["敏捷"], player_item["基础"]["力量"], player_item["成长当前"]["力量"], player_item["成长基准"]["力量"], player_item["基础"]["智力"], player_item["成长当前"]["智力"], player_item["成长基准"]["智力"], skill_txt)
            found = True
            await send_message(message, 0, 1, txt)
            return
    if found == False:
        txt = "\n【你未拥有宠物[{}]】".format(pet_name)
        await send_message(message, 0, 1, txt)
        return


async def pet_break(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    uid = await player_id(number)
    pet_name = message.content.split("宠物突破")[1]
    txt = ""
    with open (f"data/pet/{uid}.txt", 'r') as f:
        player_data = json.load(f)
    with open (f"data/pet/pet.txt", 'r') as f:
        pet_data = json.load(f)  
    for pet_item in pet_data:
        if pet_item["名称"] == pet_name:
            break
    found = False
    pet_break = False
    for player_item in player_data:
        if player_item["名称"] == pet_name:
            found = True
            stone = f"{pet_name}·精元"
            if_enough = True
            if player_item["血脉"] == 0:
                break_thing = {"血肉残渣": 100, "能量余烬": 10}
            elif player_item["血脉"] == 1:
                break_thing = {"血肉残渣": 1000, "能量余烬": 100}
            elif player_item["血脉"] == 2:
                break_thing = {"血肉残骸": 300, "能量余辉": 300, "天空粉尘": 1}
            elif player_item["血脉"] == 3:
                break_thing = {"血肉碎块": 600, "能量凝胶": 600, "天空晶石": 1}
            elif player_item["血脉"] == 4:
                break_thing = {"血肉躯壳": 1000, "能量晶髓": 1000, "天空结晶": 1}
            elif player_item["血脉"] == 5:
                break_thing = {"血肉精华": 3000, "能量源华": 3000, "天空回响": 1, stone: 1}
            elif player_item["血脉"] == 6:
                break_thing = {"生命之心": 666, "魔力之源": 666, "鸿蒙之息": 1, stone: 3}
            elif player_item["血脉"] == 7:
                break_thing = {"生命启源": 6, "魔力终焉": 6, "破灭之法": 6, "不动箴言": 6, "交织意志": 6, "浩荡之歌": 6, "混沌旋律": 1, stone: 9}
            elif player_item["血脉"] == 8:
                break_thing = {"浮生寂幻": 9, "一念万想": 9, "虚实交次": 9, "梦醒谶元": 9, stone: 99}
            for key, value in break_thing.items():
                num = await bag_enough(uid, key, value)
                if num != "够了":
                    if_enough = False
                    num = num.split("*缺")[1]
                    txt += "\n缺少[{}] × {}".format(key, num)
            if if_enough == False:
                txt += "\n————————————\n【材料不足！】\n◈宠物[{}]未进化".format(pet_name)
                await send_message(message, 0, 1, txt)
                return
            else:
                for key, value in break_thing.items():
                    await bag_reduce(uid, key, value)
                player_item["血脉"] += 1
                player_item["基础"]["体质"] = math.floor(pet_item["基础"]["体质"] * (1.5 ** player_item["血脉"]))
                player_item["基础"]["敏捷"] = math.floor(pet_item["基础"]["敏捷"] * (1.5 ** player_item["血脉"]))
                player_item["基础"]["力量"] = math.floor(pet_item["基础"]["力量"] * (1.5 ** player_item["血脉"]))
                player_item["基础"]["智力"] = math.floor(pet_item["基础"]["智力"] * (1.5 ** player_item["血脉"]))
                player_item["成长基准"]["体质"] = round(pet_item["成长基准"]["体质"] * (1.3 ** player_item["血脉"]), 2)
                player_item["成长基准"]["敏捷"] = round(pet_item["成长基准"]["敏捷"] * (1.3 ** player_item["血脉"]), 2)
                player_item["成长基准"]["力量"] = round(pet_item["成长基准"]["力量"] * (1.3 ** player_item["血脉"]), 2)
                player_item["成长基准"]["智力"] = round(pet_item["成长基准"]["智力"] * (1.3 ** player_item["血脉"]), 2)
                with open(f"data/pet/{uid}.txt", 'w') as f:
                    json.dump(player_data, f, ensure_ascii=False, indent=4)

                blood_list = {"0": "•劣等•", "1": "◈平庸◈", "2": "✽养晦✽", "3": "✾韬光✾", "4": "✧潜龙✧", "5": "✩开脉✩", "6": "♐鹰势♐", "7": "♋鸣凤♋", "8": "✡返璞✡", "9": "☯归真☯"}
                for key, value in blood_list.items():
                    if key == str(player_item["血脉"] - 1):
                        blood_word0 = value
                    if key == str(player_item["血脉"]):
                        blood_word1 = value
                txt = f"\n【[{pet_name}]突破成功！】\n血脉[{blood_word0}]➜[{blood_word1}]"
                await send_message(message, 0, 1, txt)
                return

            break
    if not found:
        txt = f"\n【你尚未拥有宠物[{pet_name}]！】"
        await send_message(message, 0, 1, txt)
        return


            

